<template>
  <div class="data-binding-debug">
    <el-card>
      <template #header>
        <span>数据绑定调试面板</span>
        <el-button style="float: right; padding: 3px 0" text @click="refreshData"> 刷新 </el-button>
      </template>

      <!-- WebSocket连接状态 -->
      <div class="debug-section">
        <h4>WebSocket连接状态</h4>
        <div class="connection-list">
          <div v-for="status in connectionStatuses" :key="status.id" class="connection-item">
            <el-tag :type="getConnectionTagType(status.status)" size="small">
              {{ status.status }}
            </el-tag>
            <span class="connection-name">{{ status.name }}</span>
            <span class="connection-details">
              消息: {{ status.messageCount }} | 错误: {{ status.errorCount }}
            </span>
          </div>
          <div v-if="connectionStatuses.length === 0" class="no-connections">暂无WebSocket连接</div>
        </div>
      </div>

      <!-- 数据点列表 -->
      <div class="debug-section">
        <h4>实时数据点 ({{ dataPoints.length }})</h4>
        <el-input
          v-model="searchKey"
          placeholder="搜索数据点ID"
          size="small"
          style="margin-bottom: 10px"
          clearable
        />
        <div class="data-points-list">
          <div
            v-for="point in filteredDataPoints"
            :key="point.id"
            class="data-point-item"
            :class="{ highlighted: point.id === highlightedPoint }"
          >
            <div class="point-header">
              <el-tag size="small" type="primary">{{ point.id }}</el-tag>
              <el-tag size="small" :type="getQualityTagType(point.quality)">
                {{ point.quality }}
              </el-tag>
              <span class="point-source">来源: {{ point.sourceId }}</span>
            </div>
            <div class="point-details">
              <span class="point-value">值: {{ point.value }}</span>
              <span class="point-type">类型: {{ point.type }}</span>
              <span class="point-time"> 更新: {{ formatTime(point.timestamp) }} </span>
            </div>
            <div v-if="point.unit" class="point-unit">单位: {{ point.unit }}</div>
          </div>
          <div v-if="filteredDataPoints.length === 0 && dataPoints.length > 0" class="no-results">
            未找到匹配的数据点
          </div>
          <div v-if="dataPoints.length === 0" class="no-data">暂无数据点</div>
        </div>
      </div>

      <!-- 组件绑定状态 -->
      <div class="debug-section">
        <h4>组件绑定状态</h4>
        <div class="binding-list">
          <div v-for="binding in componentBindings" :key="binding.id" class="binding-item">
            <div class="binding-header">
              <el-tag size="small">{{ binding.componentType }}</el-tag>
              <span class="binding-id">{{ binding.id }}</span>
            </div>
            <div v-if="binding.dataBinding?.enabled" class="binding-details">
              <div class="binding-row">
                <span class="label">数据点ID:</span>
                <el-tag
                  size="small"
                  :type="
                    isDataPointAvailable(binding.dataBinding.dataPointId) ? 'success' : 'danger'
                  "
                >
                  {{ binding.dataBinding.dataPointId }}
                </el-tag>
                <el-button
                  size="small"
                  text
                  @click="highlightDataPoint(binding.dataBinding.dataPointId)"
                >
                  定位
                </el-button>
              </div>
              <div class="binding-row">
                <span class="label">绑定属性:</span>
                <span>{{ binding.dataBinding.targetProperty }}</span>
              </div>
              <div class="binding-row">
                <span class="label">数据转换:</span>
                <span>{{ binding.dataBinding.transform }}</span>
              </div>
              <div class="binding-row">
                <span class="label">当前值:</span>
                <span class="current-value">
                  {{ getCurrentValue(binding.dataBinding.dataPointId) }}
                </span>
              </div>
            </div>
            <div v-else class="binding-disabled">数据绑定未启用</div>
          </div>
          <div v-if="componentBindings.length === 0" class="no-bindings">暂无组件绑定</div>
        </div>
      </div>

      <!-- 测试消息发送 -->
      <div class="debug-section">
        <h4>测试消息发送</h4>
        <div class="test-controls">
          <el-input
            v-model="testMessage"
            type="textarea"
            :rows="3"
            placeholder='输入测试消息，例如: {"复检实际重量值": 123}'
          />
          <el-button type="primary" @click="sendTestMessage" style="margin-top: 10px">
            发送测试消息
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRealtimeDataStore } from '@/stores/realtime-data';
import { wsManager } from '@/services/websocket';
import { globalStore } from '@/components/mt-edit/store/global';
import { ElCard, ElButton, ElTag, ElInput, ElMessage } from 'element-plus';

const realtimeStore = useRealtimeDataStore();
const searchKey = ref('');
const highlightedPoint = ref('');
const testMessage = ref('{"复检实际重量值": 123}');

// 获取WebSocket连接状态
const connectionStatuses = computed(() => {
  return realtimeStore.sourceStatus;
});

// 获取数据点列表
const dataPoints = computed(() => {
  return realtimeStore.dataPoints;
});

// 筛选数据点
const filteredDataPoints = computed(() => {
  if (!searchKey.value) {
    return dataPoints.value;
  }
  return dataPoints.value.filter((point: any) =>
    point.id.toLowerCase().includes(searchKey.value.toLowerCase())
  );
});

// 获取组件绑定状态
const componentBindings = computed(() => {
  return globalStore.done_json
    .filter((item) => item.data_binding)
    .map((item) => ({
      id: item.id,
      componentType: item.type,
      dataBinding: item.data_binding
    }));
});

// 工具函数
const getConnectionTagType = (status: string) => {
  switch (status) {
    case 'connected':
      return 'success';
    case 'connecting':
      return 'warning';
    case 'error':
      return 'danger';
    default:
      return 'info';
  }
};

const getQualityTagType = (quality: string) => {
  switch (quality) {
    case 'good':
      return 'success';
    case 'uncertain':
      return 'warning';
    case 'bad':
      return 'danger';
    default:
      return 'info';
  }
};

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString();
};

const isDataPointAvailable = (pointId: string) => {
  return dataPoints.value.some((point: any) => point.id === pointId);
};

const getCurrentValue = (pointId: string) => {
  const point = dataPoints.value.find((p: any) => p.id === pointId);
  return point ? point.value : '--';
};

const highlightDataPoint = (pointId: string) => {
  highlightedPoint.value = pointId;
  setTimeout(() => {
    highlightedPoint.value = '';
  }, 3000);
};

const refreshData = () => {
  // 触发数据刷新
  ElMessage.success('数据已刷新');
};

const sendTestMessage = () => {
  try {
    const messageData = JSON.parse(testMessage.value);

    // 模拟WebSocket消息
    const mockMessage = {
      type: 'data',
      data: messageData,
      timestamp: Date.now(),
      source: 'debug_test'
    };

    // 直接处理消息
    realtimeStore.handleWebSocketMessage(mockMessage);

    ElMessage.success('测试消息已发送');
  } catch (error) {
    ElMessage.error('测试消息格式错误: ' + (error as Error).message);
  }
};

// 定时刷新数据（可选）
let refreshTimer: number | null = null;

onMounted(() => {
  // 每5秒刷新一次状态
  refreshTimer = window.setInterval(() => {
    // 这里可以添加定时刷新逻辑
  }, 5000);
});

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
});
</script>

<style scoped>
.data-binding-debug {
  max-width: 100%;
}

.debug-section {
  margin-bottom: 20px;
}

.debug-section h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
}

.connection-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.connection-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.connection-name {
  font-weight: 500;
}

.connection-details {
  font-size: 12px;
  color: #6c757d;
  margin-left: auto;
}

.no-connections,
.no-results,
.no-data,
.no-bindings {
  text-align: center;
  color: #6c757d;
  font-size: 13px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.data-points-list {
  max-height: 300px;
  overflow-y: auto;
}

.data-point-item {
  padding: 10px;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: all 0.2s;
}

.data-point-item.highlighted {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.point-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.point-source {
  font-size: 12px;
  color: #6c757d;
  margin-left: auto;
}

.point-details {
  display: flex;
  gap: 15px;
  font-size: 13px;
  color: #495057;
}

.point-value {
  font-weight: 600;
  color: #2c3e50;
}

.point-unit {
  font-size: 12px;
  color: #6c757d;
  margin-top: 4px;
}

.binding-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.binding-item {
  padding: 12px;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  background: #f8f9fa;
}

.binding-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.binding-id {
  font-weight: 500;
  color: #2c3e50;
}

.binding-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.binding-row {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
}

.binding-row .label {
  color: #6c757d;
  min-width: 80px;
}

.current-value {
  font-weight: 600;
  color: #409eff;
}

.binding-disabled {
  color: #6c757d;
  font-style: italic;
  font-size: 13px;
}

.test-controls {
  display: flex;
  flex-direction: column;
}
</style>
